package com.jxwifi.cloud.quickcleanserver.workmap;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusPath;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RidePath;
import com.amap.api.services.route.RideRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkRouteResult;
import com.basicactivity.BasicActivity;
import com.idroid.utils.NoDoubleClickListener;
import com.idroid.widget.LoadDialog;
import com.jxwifi.cloud.quickcleanserver.R;
import com.jxwifi.cloud.quickcleanserver.app.AccountMgr;
import com.jxwifi.cloud.quickcleanserver.app.CleanBasicActivity;
import com.jxwifi.cloud.quickcleanserver.app.StateUtils;
import com.jxwifi.cloud.quickcleanserver.app.UrlPool;
import com.jxwifi.cloud.quickcleanserver.bean.DetailsBean;
import com.jxwifi.cloud.quickcleanserver.bean.InfoBean;
import com.jxwifi.cloud.quickcleanserver.bean.OrderFromBean;
import com.jxwifi.cloud.quickcleanserver.bean.SystemBean;
import com.jxwifi.cloud.quickcleanserver.chronograph.ChronographActivity;
import com.jxwifi.cloud.quickcleanserver.login.LoginActivity;
import com.jxwifi.cloud.quickcleanserver.mycenter.AuthenticationActivity;
import com.jxwifi.cloud.quickcleanserver.okhttp.AuzHttp;
import com.jxwifi.cloud.quickcleanserver.okhttp.DataJson_Cb;
import com.jxwifi.cloud.quickcleanserver.okhttp.Params;
import com.jxwifi.cloud.quickcleanserver.utils.INavigation;
import com.jxwifi.cloud.quickcleanserver.utils.KAlertDialog;
import com.jxwifi.cloud.quickcleanserver.utils.LocationGaoDe;
import com.jxwifi.cloud.quickcleanserver.utils.NaviContext;
import com.jxwifi.cloud.quickcleanserver.utils.PasswordLogin;
import com.jxwifi.cloud.quickcleanserver.utils.ToBaidu;
import com.jxwifi.cloud.quickcleanserver.utils.ToBaiduWeb;
import com.jxwifi.cloud.quickcleanserver.utils.ToGaode;
import com.jxwifi.cloud.quickcleanserver.utils.ToastUtils;
import com.jxwifi.cloud.quickcleanserver.utils.TokenTimeUtils;
import com.jxwifi.cloud.quickcleanserver.workmap.mapUtils.BusRouteOverlay;
import com.jxwifi.cloud.quickcleanserver.workmap.mapUtils.DrivingRouteOverlay;
import com.jxwifi.cloud.quickcleanserver.workmap.mapUtils.RideRouteOverlay;

import java.text.DecimalFormat;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 地图显示
 * Created by Administrator on 2019/5/14.
 */

public class MapWorkActivity extends CleanBasicActivity implements RouteSearch.OnRouteSearchListener {

    @Bind(R.id.mp_map_work)
    MapView mMapView;
    //初始化地图控制器对象
    AMap aMap;

    @Bind(R.id.tv_map_work_time)
    TextView mTvMapWorkTime;//时间
    @Bind(R.id.tv_map_work_distance)
    TextView mTvMapWorkDistance;//公里
    @Bind(R.id.tv_map_work_income)
    TextView mTvMapWorkIncome;//价格
    @Bind(R.id.tv_map_work_service_type_text)
    TextView mTvMapWorkServiceTypeText;//服务类型
    @Bind(R.id.tv_map_work_order_type_text)
    TextView mTvMapWorkOrderTypeText;//状态
    @Bind(R.id.tv_form_order_service_time_text)
    TextView mTvFormOrderServiceTiemText;//服务时间
    @Bind(R.id.tv_map_work_order_address_text)
    TextView mTvMapWorkOrderAddressText;//服务地址
    @Bind(R.id.tv_map_work_measure_text)
    TextView mTvMapWorkMeasureText;//面积
    @Bind(R.id.tv_map_work_cost_text)
    TextView mTvMapWorkCostText;//金额
    @Bind(R.id.lin_map_work_cost)
    LinearLayout mLinMapWorkCost;
    @Bind(R.id.tv_map_work_time_hours)
    TextView mTvMapWorkTimeHours;
    @Bind(R.id.tv_img_map_work_phone)
    TextView mTvImgMapWorkPhone; //电话
    @Bind(R.id.tv_map_work_income_text)
    TextView mTvMapWorkInComeText;
    @Bind(R.id.tv_map_work_income_yuan)
    TextView mTvMapWorkInComeYuan;
    @Bind(R.id.tv_map_work_remarks_text)
    TextView mTvMapWorkRemarksText;
    @Bind(R.id.lin_map_work_remarks)
    LinearLayout mLinMapWorkRemarks;
    @Bind(R.id.tv_map_work_order_codee_text)
    TextView mTvMapWorkOrderCodeText;
    @Bind(R.id.lin_map_work)
    LinearLayout mLinMapWork;

    @Bind(R.id.tv_chro_return_back)
    TextView mTvChroReturnBack;//出发 到达 开始工作 按钮
    @Bind(R.id.rel_map_navigation)
    RelativeLayout mTvNavigation;//开始导航

    private String mOrderCode;
    private OrderFromBean morderFromBean;
    private long mleave;
    private float rideDistance;

    private LoadDialog mLoadDialog;
    private RouteSearch routeSearch;
    //rel_img_map_work_phone

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_work);
        ButterKnife.bind(this);
        openEventBus();
        mLoadDialog = new LoadDialog(mBaseContext);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        mOrderCode = getIntent().getStringExtra("order_code");
        rideDistance = getIntent().getFloatExtra("rideDistance",0);
        routeSearch = new RouteSearch(this);
        routeSearch.setRouteSearchListener(this);

        refreshlocation();
        mLoadDialog.show();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                intidata();
            }
        }, 1000);
    }

    @OnClick({R.id.tv_chro_return_back, R.id.tv_map_navigation, R.id.rel_img_back_pressed
    ,R.id.rel_img_map_work_phone})
    void clickCK(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            ///出发 到达 开始工作
            case R.id.tv_chro_return_back:
                if (StateUtils.DP_ING.equals(morderFromBean.getOrderStatus())) { //接单

                    if ("00:00".equals(mTvMapWorkTime.getText().toString())) {
                        Toast toast = Toast.makeText(mBaseContext, "服务时间已超时，不可接单", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast, 3000);
                        return;
                    }

                    if (AccountMgr.isLogin(mBaseContext)) {
                        if (!StateUtils.YES.equals(AccountMgr.getIsAuth(mBaseContext))) {
                            intent.setClass(mBaseContext, AuthenticationActivity.class);
                            startActivity(intent);
                            return;
                        } else if (morderFromBean.getCleanerCode()!=null){
                            if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                                Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                                ToastUtils.showMyToast(toast,3000);
                                return;
                            }
                        }else {
                            initgrab();
                        }
                    } else {
                        startActivity(new Intent(mBaseContext, LoginActivity.class));
                    }
                } else if (StateUtils.SER_START.equals(morderFromBean.getOrderStatus())) { //点击出发操作

                    if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                        Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                        return;
                    }

                    final KAlertDialog dialogshow=new KAlertDialog(mBaseContext,"确认是否要出发");
                    dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
                        @Override
                        protected void onNoDoubleClick(View v) {

                            initleaves();
                            dialogshow.dismiss();
                        }
                    });
                    dialogshow.show();

                } else if (StateUtils.SER_LEAVE.equals(morderFromBean.getOrderStatus())) { //点击到达操作

                    if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                        Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                        return;
                    }

                    final KAlertDialog dialogshow=new KAlertDialog(mBaseContext,"确认是否已到达");
                    dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
                        @Override
                        protected void onNoDoubleClick(View v) {
                            initarrive();
                            dialogshow.dismiss();
                        }
                    });
                    dialogshow.show();


                    //先注释，不利于测试验证，等上线后需要放开这功能。
                    /*if (morderFromBean.getDistance()*1000>300){//验证保洁员位置是否在客服位置附近300米
                        Toast.makeText(mBaseContext, "距离目的地大于300米，不可点击到达", Toast.LENGTH_SHORT).show();
                    }else{
                        initarrive();
                    }*/
                } else if (StateUtils.SER_ARRIVE.equals(morderFromBean.getOrderStatus())) { //点击开始工作跳转计时页面
                    if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                        Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                        return;
                    }
                    final KAlertDialog dialogshow=new KAlertDialog(mBaseContext,"确认是否开始工作");
                    dialogshow.setRightTxt("确定", new NoDoubleClickListener() {
                        @Override
                        protected void onNoDoubleClick(View v) {

                            initworkstart();
                            dialogshow.dismiss();

                        }
                    });
                    dialogshow.show();

                }else if(StateUtils.CANCEL.equals(morderFromBean.getOrderStatus())||
                        StateUtils.OUT_TIME_CANCEL.equals(morderFromBean.getOrderStatus())){
                    Toast toast =Toast.makeText(mBaseContext, "订单已取消，不可操作", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                break;
            //开始导航
            case R.id.tv_map_navigation:
                if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                    Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                SparseArray<INavigation> navis = new SparseArray<INavigation>();
                navis.put(NaviContext.Navi_baidu, new ToBaidu(morderFromBean.getAddress()));
                navis.put(NaviContext.Navi_baidu_web, new ToBaiduWeb(morderFromBean.getAddress()));
                navis.put(NaviContext.Navi_gaode, new ToGaode(morderFromBean.getAddress()));
                NaviContext naviContext = new NaviContext(navis, morderFromBean.getLon(), morderFromBean.getLat());
                if (!naviContext.startAutonavi(mBaseContext)) {
                    naviContext.need2Select(this, v);
                    break;
                }
                break;
            //电话
            /*case R.id.tv_img_map_work_phone:
                if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                    Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast,3000);
                    return;
                }
                tellPhone();
                break;*/
            case R.id.rel_img_map_work_phone:
                if (!StateUtils.DP_ING.equals(morderFromBean.getOrderStatus())){
                    if (!AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                        Toast toast =Toast.makeText(mBaseContext, "订单已被抢，不可操作", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast,3000);
                        return;
                    }
                    tellPhone();
                }
                break;
            case R.id.rel_img_back_pressed:
                onBackPressed();
                break;
        }
    }

    public void initView() {

        //每次进来就更新下用户信息
        if (AccountMgr.isLogin(mBaseContext)) {
            memberinfo();
        }
        mLinMapWork.setVisibility(View.VISIBLE);
        float mestimate = Float.valueOf(morderFromBean.getPrices()) * morderFromBean.getExpectHours();
        DecimalFormat myformat = new DecimalFormat("0.00");
        SpannableString styledText = new SpannableString("" + myformat.format(mestimate));
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style0), 0, myformat.format(mestimate).indexOf(".") + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        styledText.setSpan(new TextAppearanceSpan(this, R.style.style1), myformat.format(mestimate).indexOf(".") + 1, myformat.format(mestimate).length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);


            //优化处理
        if (AccountMgr.isLogin(mBaseContext)){
            if (morderFromBean.getCleanerCode()!=null){
                if (AccountMgr.getCleanerCode(mBaseContext).equals(morderFromBean.getCleanerCode())){
                    initbuttonshow();
                }else{
                    mTvChroReturnBack.setText("订单已被抢，不可操作");
                    if (StateUtils.DP_ING.equals(morderFromBean.getOrderStatus())) {
                        mTvNavigation.setVisibility(View.GONE);
                        mTvMapWorkOrderTypeText.setText("已支付订金");
                    } else if (StateUtils.SER_START.equals(morderFromBean.getOrderStatus())) {
                        mTvNavigation.setVisibility(View.GONE);
                        mTvMapWorkOrderTypeText.setText("已接单");
                    } else if (StateUtils.SER_LEAVE.equals(morderFromBean.getOrderStatus())) {
                        mTvNavigation.setVisibility(View.VISIBLE);
                        mTvMapWorkOrderTypeText.setText("已出发");
                    } else if (StateUtils.SER_ARRIVE.equals(morderFromBean.getOrderStatus())) {
                        mTvNavigation.setVisibility(View.GONE);
                        mTvMapWorkOrderTypeText.setText("已到达");
                    }
                }
            }else{
                initbuttonshow();
            }
        }else{
            initbuttonshow();
        }
        if (StateUtils.DP_ING.equals(morderFromBean.getOrderStatus())) {
            mTvMapWorkIncome.setText(styledText);
            mLinMapWorkCost.setVisibility(View.GONE);
            mTvImgMapWorkPhone.setVisibility(View.GONE);
            mTvMapWorkInComeText.setVisibility(View.VISIBLE);
            mTvMapWorkInComeYuan.setVisibility(View.VISIBLE);
            mTvMapWorkIncome.setVisibility(View.VISIBLE);
        } else {
            mLinMapWorkCost.setVisibility(View.VISIBLE);
            mTvMapWorkCostText.setText(myformat.format(mestimate) + "元");
            mTvImgMapWorkPhone.setVisibility(View.VISIBLE);
            mTvMapWorkInComeText.setVisibility(View.GONE);
            mTvMapWorkInComeYuan.setVisibility(View.GONE);
            mTvMapWorkIncome.setVisibility(View.GONE);
        }


        //换算时间  服务的时间为：serviceTime 系统时间：now TokenTimeUtils.newTime(mAskBean.getServiceTime(),mAskBean.getNow())
        String mServiceTime = TokenTimeUtils.newTime(morderFromBean.getServiceTime(), morderFromBean.getNow());
        if (mServiceTime.indexOf(":") != -1) {
            mTvMapWorkTimeHours.setText("小时");
            mTvMapWorkTime.setText(mServiceTime);
        } else {
            mTvMapWorkTime.setText(mServiceTime);
            mTvMapWorkTimeHours.setText("天");
        }

        //DistanceOfTwoPoints
        //double disprovn = DistanceOfTwoPoints(LocationGaoDe.getLatitude(), LocationGaoDe.getLongitude(), Double.valueOf(morderFromBean.getLat()), Double.valueOf(morderFromBean.getLon())) / 1000;
        if (rideDistance > 1) {
            DecimalFormat format = new DecimalFormat("#0.00");
            String str = format.format(rideDistance);
            mTvMapWorkDistance.setText(str);
        } else {
            mTvMapWorkDistance.setText("<1");
        }
        mTvMapWorkServiceTypeText.setText(morderFromBean.getProductName());
        mTvFormOrderServiceTiemText.setText(morderFromBean.getServiceTime());
        mTvMapWorkOrderAddressText.setText(morderFromBean.getProvince() + "" + morderFromBean.getCity() + morderFromBean.getArea() + "" + "" + morderFromBean.getAddress());
        mTvMapWorkMeasureText.setText(morderFromBean.getAreaSize());
        mTvMapWorkOrderCodeText.setText(morderFromBean.getOrderCode());
        if (TextUtils.isEmpty(morderFromBean.getRemark())) {
            mLinMapWorkRemarks.setVisibility(View.GONE);
        } else {
            mLinMapWorkRemarks.setVisibility(View.VISIBLE);
            mTvMapWorkRemarksText.setText(morderFromBean.getRemark());
        }
    }

    public void initbuttonshow(){
        if (StateUtils.DP_ING.equals(morderFromBean.getOrderStatus())) {
            mTvChroReturnBack.setText("接单");
            mTvNavigation.setVisibility(View.GONE);
            mTvMapWorkOrderTypeText.setText("已支付订金");
        } else if (StateUtils.SER_START.equals(morderFromBean.getOrderStatus())) {
            mTvChroReturnBack.setText("出发");
            mTvNavigation.setVisibility(View.GONE);
            mTvMapWorkOrderTypeText.setText("已接单");
        } else if (StateUtils.SER_LEAVE.equals(morderFromBean.getOrderStatus())) {
            mTvChroReturnBack.setText("到达");
            mTvNavigation.setVisibility(View.VISIBLE);
            mTvMapWorkOrderTypeText.setText("已出发");
        } else if (StateUtils.SER_ARRIVE.equals(morderFromBean.getOrderStatus())) {
            mTvChroReturnBack.setText("开始工作");
            mTvNavigation.setVisibility(View.GONE);
            mTvMapWorkOrderTypeText.setText("已到达");
        }else if (StateUtils.CANCEL.equals(morderFromBean.getOrderStatus())||
                StateUtils.OUT_TIME_CANCEL.equals(morderFromBean.getOrderStatus())){
            mTvChroReturnBack.setText("订单已取消");
            mTvNavigation.setVisibility(View.GONE);
            mTvMapWorkOrderTypeText.setText("已取消");
        }
    }

    public void intidata() {
        Params params = new Params();
        params.add("orderCode", mOrderCode);
        AuzHttp.get(UrlPool.GET_ORDER_INFO_CLEANER, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    DetailsBean mdetailsBean = JSON.parseObject(data, DetailsBean.class);
                    morderFromBean = mdetailsBean.getOrderInfo();
                    initView();

                    setRouteCarListener(3);

                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        intidata();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                mLoadDialog.dismiss();
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        }, TAG);
    }

    //抢单操作
    public void initgrab() {
        mLoadDialog.show();
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", mOrderCode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_GRAB, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    morderFromBean = JSON.parseObject(data, OrderFromBean.class);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mLoadDialog.dismiss();
                        }
                    }, 500);
                    initView();
                    Toast toast = Toast.makeText(mBaseContext, "抢单成功", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initgrab();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
                intidata();
                mLoadDialog.dismiss();
            }
        }, TAG);
    }

    //出发操作
    public void initleave() {
        mLoadDialog.show();
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", mOrderCode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_LEAVE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    morderFromBean.setOrderStatus(StateUtils.SER_LEAVE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mLoadDialog.dismiss();
                        }
                    }, 500);
                    initView();
                    Toast toast = Toast.makeText(mBaseContext, "开始出发", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initleave();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
                intidata();
                mLoadDialog.dismiss();
            }
        }, TAG);
    }

    //到达
    public void initarrive() {
        mLoadDialog.show();
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", mOrderCode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_ARRIVE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    morderFromBean.setOrderStatus(StateUtils.SER_ARRIVE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mLoadDialog.dismiss();
                        }
                    }, 500);
                    initView();
                    Toast toast = Toast.makeText(mBaseContext, "到达目的地", Toast.LENGTH_SHORT);
                    ToastUtils.showMyToast(toast, 3000);
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initarrive();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
                intidata();
                mLoadDialog.dismiss();
            }
        }, TAG);
    }

    //开始工作
    public void initworkstart() {
        Params params = new Params();
        params.add("lat", LocationGaoDe.getLatitude());
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("orderCode", mOrderCode);
        AuzHttp.post(UrlPool.POST_CLEANER_OPT_START, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    morderFromBean = JSON.parseObject(data, OrderFromBean.class);
                    //initView();
                    Intent intent = new Intent();
                    intent.setClass(mBaseContext, ChronographActivity.class);
                    intent.putExtra("order_code", mOrderCode);
                    startActivity(intent);
                    finish();
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initworkstart();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
                intidata();
            }
        }, TAG);
    }

    //出发的条件判断
    public void initleaves() {
        Params params = new Params();
        AuzHttp.get(UrlPool.SYSTEM_LIST, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) { //正常数据
                    List<SystemBean> msystemBean = JSON.parseArray(data, SystemBean.class);
                    for (int i = 0; i < msystemBean.size(); i++) {
                        if ("kjb_order_leave_time".equals(msystemBean.get(i).getKeyName())) {
                            mleave = (long) Integer.valueOf(msystemBean.get(i).getKeyValue());
                            break;
                        }
                    }
                    //判断服务时间与本地时间差是否大于2小时
                    if (TokenTimeUtils.isContrast(morderFromBean.getServiceTime(), mleave)) {
                        if (StateUtils.ing_order.equals(AccountMgr.getacceptStatus(mBaseContext))) {
                            Toast toast = Toast.makeText(mBaseContext, "您有订单需要工作，不可再出发", Toast.LENGTH_SHORT);
                            ToastUtils.showMyToast(toast, 3000);
                        } else if (StateUtils.close_order.equals(AccountMgr.getacceptStatus(mBaseContext))) {
                            Toast toast = Toast.makeText(mBaseContext, "休息状态下，不可出发", Toast.LENGTH_SHORT);
                            ToastUtils.showMyToast(toast, 3000);
                        } else {
                            initleave();
                        }
                    } else {
                        Toast toast = Toast.makeText(mBaseContext, "服务时间大于" + (mleave / 60) + "小时前不可出发", Toast.LENGTH_SHORT);
                        ToastUtils.showMyToast(toast, 3000);
                    }

                } else {//请他情况做密码登录接口请求操作后再次请求接口
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        initleaves();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        }, TAG);
    }

    //虚拟电话号码
    public void tellPhone() {
        Params params = new Params();
        params.add("orderCode", morderFromBean.getOrderCode());
        AuzHttp.get(UrlPool.GET_SECRENO_GENERATE, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {
                    if (!TextUtils.isEmpty(data)) {
                        Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                        Uri murldata = Uri.parse("tel:" + data.replace("\\", ""));
                        mTelintent.setData(murldata);
                        startActivity(mTelintent);
                    } else {
                        Intent mTelintent = new Intent(Intent.ACTION_DIAL);
                        Uri murldata = Uri.parse("tel:" + morderFromBean.getUserTell().replace("\\", ""));
                        mTelintent.setData(murldata);
                        startActivity(mTelintent);
                    }
                } else {
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        tellPhone();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        }, TAG);
    }

    public void memberinfo() {
        AuzHttp.get(UrlPool.GET_UCCLEANER_INFO, new Params(), new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {
                if (code == 0) {//正常数据
                    InfoBean mInfoBean = JSON.parseObject(data, InfoBean.class);
                    AccountMgr.putUser(mBaseContext, mInfoBean, false);
                } else {//请他情况做密码登录接口请求操作后再次请求接口
                    PasswordLogin.passwordlogin(mBaseContext, TAG, AccountMgr.gettell(mBaseContext), AccountMgr.getpassword(mBaseContext));
                    if (PasswordLogin.mIsLogin) {
                        memberinfo();
                    }
                }
            }

            @Override
            public void onFailure(int errorCode, String msg) {
                Toast toast = Toast.makeText(mBaseContext, msg, Toast.LENGTH_SHORT);
                ToastUtils.showMyToast(toast, 3000);
            }
        }, TAG);
    }

    public void refreshlocation() {
        Params params = new Params();
        params.add("lon", LocationGaoDe.getLongitude());
        params.add("lat", LocationGaoDe.getLatitude());
        AuzHttp.get(UrlPool.UPDATE_REAL_LOCATION, params, new DataJson_Cb() {
            @Override
            public void onSuccess(int code, String data) {

            }

            @Override
            public void onFailure(int errorCode, String msg) {

            }
        }, "");
    }

    /**
     * 规划线路
     * type 0 驾车 1 公交 2 步行 3 骑行
     *
     * @param type
     */
    private void setRouteCarListener(int type) {
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        //清除防止重复显示
        aMap.clear();
        //模拟起始点与目的经纬度（如：深圳市）
        RouteSearch.FromAndTo fromAndTo = new RouteSearch.FromAndTo(new LatLonPoint(LocationGaoDe.getLatitude(), LocationGaoDe.getLongitude()),
                new LatLonPoint(Double.valueOf(morderFromBean.getLat()), Double.valueOf(morderFromBean.getLon())));
        Log.w("oushuhua", "lat=" + LocationGaoDe.getLatitude() + "lon=" + LocationGaoDe.getLongitude() + "citycode" + LocationGaoDe.getCityCode());
        Log.w("oushuhua", "lat1=" + Double.valueOf(morderFromBean.getLat()) + "lon1=" + Double.valueOf(morderFromBean.getLon()));

        //驾车：第一个参数表示fromAndTo包含路径规划的起点和终点，drivingMode表示驾车模式(支持20种模式  -在PathPlanningStrategy类中定义)
        //第三个参数表示途经点（最多支持16个），第四个参数表示避让区域（最多支持32个），第五个参数表示避让道路
        //模式链接：http://lbs.amap.com/api/android-navi-sdk/guide/route-plan/drive-route-plan
       /* LatLng marker1 = new LatLng(((22.5587+22.5587)/2), (119.8727+113.8950)/2);
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker1));*/
        if (type == 0) {
            RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, RouteSearch.DrivingDefault, null,
                    null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
            routeSearch.calculateDriveRouteAsyn(query);
        } else if (type == 1) {
            //公交：fromAndTo包含路径规划的起点和终点，RouteSearch.BusLeaseWalk表示公交查询模式
            //第三个参数表示公交查询城市区号，第四个参数表示是否计算夜班车，0表示不计算,1表示计算
            RouteSearch.BusRouteQuery query1 = new RouteSearch.BusRouteQuery(fromAndTo, RouteSearch.BusLeaseWalk, LocationGaoDe.getCityCode(), 1);
            //
            routeSearch.calculateBusRouteAsyn(query1);

        } else if (type == 2) {

        } else if (type == 3) {
            RouteSearch.RideRouteQuery query3 = new RouteSearch.RideRouteQuery(
                    fromAndTo, RouteSearch.RidingDefault);
            routeSearch.calculateRideRouteAsyn(query3);
        }
    }

    //公交路线设置
    @Override
    public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {
        if (i == 1000) {
            if (busRouteResult.getPaths().size() != 0) {
                BusPath busPath = busRouteResult.getPaths().get(0);//取数据泪飙中的第一条数据
                setBusRoute(busPath, busRouteResult.getStartPos(), busRouteResult.getTargetPos());
                float distance = busPath.getDistance() / 1000;
                long duration = busPath.getDuration() / 60;
                //需步行距离
                float walkdistance = busPath.getWalkDistance() / 1000;
                //行车的距离
                float busdistance = busPath.getBusDistance() / 1000;
                //成本、费用（其中walkdistance+busdistance=distance 行车+步行=总距离）
                float cost = busPath.getCost();
                //content.setText("\n距离/公里：" + distance + "\n时间/分：" + duration + "\n步行距离/公里：" + walkdistance + "\n行车距离/公里：" + busdistance + "\n成本、费用：" + cost);
            } else {
                LatLng latLng = new LatLng(Double.valueOf(morderFromBean.getLat()),
                        Double.valueOf(morderFromBean.getLon()));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }
        } else {
            Log.e(TAG, "onBusRouteSearched: 路线规划失败");
        }
    }

    //驾车路线设置
    @Override
    public void onDriveRouteSearched(DriveRouteResult driveRouteResult, int i) {
        if (i == 1000) {
            if (driveRouteResult.getPaths().size() != 0) {
                DrivePath drivePath = driveRouteResult.getPaths().get(0);//取数据泪飙中的第一条数据
                DriveRouteResult mDriveRouteResult = driveRouteResult;
                //setDriveRoute(busPath, driveRouteResult.getStartPos(), driveRouteResult.getTargetPos());
                DrivingRouteOverlay drivingRouteOverlay = new DrivingRouteOverlay(
                        mBaseContext, aMap, drivePath,
                        mDriveRouteResult.getStartPos(),
                        mDriveRouteResult.getTargetPos(), null);
                drivingRouteOverlay.setNodeIconVisibility(false);//设置节点marker是否显示
                drivingRouteOverlay.setIsColorfulline(true);//是否用颜色展示交通拥堵情况，默认true
                drivingRouteOverlay.removeFromMap();
                drivingRouteOverlay.addToMap();
                drivingRouteOverlay.zoomToSpan();
            } else {
                LatLng latLng = new LatLng(Double.valueOf(morderFromBean.getLat()),
                        Double.valueOf(morderFromBean.getLon()));
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));
            }

        } else {
            Log.e(TAG, "onBusRouteSearched: 路线规划失败");
        }

    }

    //步行路线设置
    @Override
    public void onWalkRouteSearched(WalkRouteResult walkRouteResult, int i) {

    }

    //骑车路线设置
    @Override
    public void onRideRouteSearched(RideRouteResult rideRouteResult, int i) {
        if (i == 1000) {
            RidePath ridePath = rideRouteResult.getPaths().get(0);
            setRideRoute(ridePath, rideRouteResult.getStartPos(), rideRouteResult.getTargetPos());
            float distance = ridePath.getDistance() / 1000;
            long duration = ridePath.getDuration() / 60;
            if (distance > 1) {
                DecimalFormat format = new DecimalFormat("#0.00");
                String str = format.format(rideDistance);
                mTvMapWorkDistance.setText(str);
            } else {
                mTvMapWorkDistance.setText("<1");
            }

        } else {
            Log.i(TAG, "onRideRouteSearched: 路线规划失败");
        }
        mLoadDialog.dismiss();
    }

    /**
     * 公交规划线路
     */
    private void setBusRoute(BusPath busPath, LatLonPoint start, LatLonPoint end) {
        BusRouteOverlay busRouteOverlay = new BusRouteOverlay(this, aMap, busPath, start, end);
        busRouteOverlay.removeFromMap();//去掉DriveLineOverlay上的线段和标记。
        busRouteOverlay.addToMap();//添加驾车路线添加到地图上显示。
        busRouteOverlay.zoomToSpan();//移动镜头到当前的视角。
        busRouteOverlay.setNodeIconVisibility(true);//是否显示路段节点图标
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * 骑行规划线路
     */
    private void setRideRoute(RidePath ridePath, LatLonPoint start, LatLonPoint end) {
        RideRouteOverlay rideRouteOverlay = new RideRouteOverlay(this, aMap, ridePath, start, end);
        rideRouteOverlay.removeFromMap();
        rideRouteOverlay.addToMap();
        rideRouteOverlay.zoomToSpan();
    }


    private static final double EARTH_RADIUS = 6378137;

    public static double DistanceOfTwoPoints(double lat1, double lng1,
                                             double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }
}
